package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.Repository.StrategyTemplateRepository;
import cn.wolfcode.luowowo.search.domain.StrategyTemplate;
import cn.wolfcode.luowowo.search.query.StrategySearchQuery;
import cn.wolfcode.luowowo.search.service.IStrategySearchService;
import cn.wolfcode.luowowo.search.vo.StatisVO;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregation;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.TermsValuesSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.*;

@Service
public class StrategySearchServiceImpl implements IStrategySearchService {

    @Autowired
    private StrategyTemplateRepository repository;

    public void save(StrategyTemplate strategyTemplate) {
        repository.save(strategyTemplate);
    }

    public List<StatisVO> getStatisVo(String s1, String s2, String s3,BoolQueryBuilder q) {
        //分组查询的字段
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();
        TermsValuesSourceBuilder sourceBuilder = new TermsValuesSourceBuilder("id");
        sourceBuilder.field(s1);
        TermsValuesSourceBuilder sourceBuilder1 = new TermsValuesSourceBuilder("name");
        sourceBuilder1.field(s2);
        sources.add(sourceBuilder);
        sources.add(sourceBuilder1);
        //分组条件
        CompositeAggregationBuilder compositeAggregationBuilder = new CompositeAggregationBuilder(s3, sources);
        //条件对象
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.addAggregation(compositeAggregationBuilder);
        builder.withPageable(PageRequest.of(0, 1));

        if (q != null) {
            builder.withQuery(q);
        }
        //分组查询的数据
        AggregatedPage<StrategyTemplate> aggregatedPage = (AggregatedPage<StrategyTemplate>) repository.search(builder.build());
        CompositeAggregation groupByTheme = aggregatedPage.getAggregations().get(s3);
        List<? extends CompositeAggregation.Bucket> buckets = groupByTheme.getBuckets();
        //封装主题对象
        List<StatisVO> themes = new ArrayList<>();
        for (CompositeAggregation.Bucket bucket : buckets) {
            Long id = Long.parseLong(bucket.getKey().get("id").toString());
            String name = bucket.getKey().get("name").toString();
            long docCount = bucket.getDocCount();
            StatisVO statisVO = new StatisVO(id, name, docCount);
            themes.add(statisVO);
        }
        return themes;
    }


    //查询主题推荐
    public List<Map<String, Object>> queryThemeCommed() {
        List<Map<String, Object>> data = new ArrayList<>();
        List<StatisVO> themes = getStatisVo("themeId", "themeName","groupByTheme",null);

        //排序(从大带小)
        Collections.sort(themes, new Comparator<StatisVO>() {
            public int compare(StatisVO o1, StatisVO o2) {
                //如果为o1 - o2 那么就是正序
                return (int) (o2.getCount() - o1.getCount());
            }
        });

        //截取10个
        if (themes.size() > 10) {
            themes = themes.subList(0, 9);
        }

        //查询关联地并封装到map中
        for (StatisVO theme : themes) {
            Map<String, Object> map = new HashMap<>();
            map.put("theme", theme);
            List<StatisVO> dests = this.getDests(theme.getId());
            map.put("dests", dests);
            data.add(map);
        }
        return data;
    }

    //查询关联地
    public List<StatisVO> getDests(Long id) {
        List<StrategyTemplate> strategyTemplates = repository.findByThemeId(id);
        //定义该list,用户去重
        List<String> names = new ArrayList<>();
        List<StatisVO> list = new ArrayList<>();
        for (StrategyTemplate strategyTemplate : strategyTemplates) {
            if (!names.contains(strategyTemplate.getDestName())) {
                StatisVO statisVO = new StatisVO();
                statisVO.setId(strategyTemplate.getDestId());
                statisVO.setName(strategyTemplate.getDestName());
                list.add(statisVO);
                names.add(strategyTemplate.getDestName());
            }
        }
        return list;
    }

    //获取国内省份推荐
    public List<StatisVO> queryChinaCommed() {
        List<StatisVO> statisVo = this.getStatisVo("provinceId", "provinceName","groupByProvince",null);
        return statisVo;
    }

    //国外国家推荐
    public List<StatisVO> queryAbroadsCommed() {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("countryId", 1));
        List<StatisVO> statisVo = this.getStatisVo("countryId", "countryName","groupByCountry",queryBuilder);
        return statisVo;
    }

    //主题推荐
    public List<StatisVO> queryThemesCommed() {
        List<StatisVO> statisVo = this.getStatisVo("themeId", "themeName","groupByTheme",null);
        return statisVo;
    }

    //分页条件查询
    public Page query(StrategySearchQuery qo) {
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //判断是否为null
        if (qo.getType() == null) {
            return repository.search(null, qo.getPageRequest());
        }

        if (qo.getType() == StrategySearchQuery.CONDITION_TYPE_CHINA) {
            //国内
            builder.must(QueryBuilders.termQuery("provinceId", qo.getTypeValue()));
        } else if (qo.getType() == StrategySearchQuery.CONDITION_TYPE_ABROAD) {
            //国外
            builder.must(QueryBuilders.termQuery("countryId", qo.getTypeValue()));
        } else if (qo.getType() == StrategySearchQuery.CONDITION_TYPE_THEME) {
            //主题
            builder.must(QueryBuilders.termQuery("themeId", qo.getTypeValue()));
        }
        //分页查询
        return repository.search(builder, qo.getPageRequest());
    }

    public List<StrategyTemplate> findByDestName(String name) {
        return repository.findByDestName(name);
    }
}
